package com.techwells.taco.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.View;

public class MxxBlurView extends View {

	int radius = 30;
	private Canvas mCanvas;
	private Bitmap mBitmap;
	private Rect mRectVisibleGlobal;
	private Matrix mMatrixScale;
	private Matrix mMatrixScaleInv;
	float BITMAP_SCALE_FACTOR = 0.2f;

	public MxxBlurView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public MxxBlurView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public MxxBlurView(Context context) {
		super(context);
		init();
	}

	// 进行一次高斯模糊
	@SuppressWarnings("deprecation")
	public void drawBlurOnce() {
		drawOffscreenBitmap(this);
		this.setBackgroundDrawable(new BitmapDrawable(FastBlur.doBlur(mBitmap,
				radius, true)));
	}

	private void init() {
		mMatrixScale = new Matrix();
		mMatrixScaleInv = new Matrix();
		mCanvas = new Canvas();
		mRectVisibleGlobal = new Rect();
		radius = dip2px(getContext(), radius);
		radius = Math.round(radius * BITMAP_SCALE_FACTOR);
	}

	// 把该View后面的一层绘制为bitmap
	public Bitmap drawOffscreenBitmap(View mView) {

		mView.getGlobalVisibleRect(mRectVisibleGlobal);

		int width = Math.round(mView.getWidth() * BITMAP_SCALE_FACTOR);
		int height = Math.round(mView.getHeight() * BITMAP_SCALE_FACTOR);

		// This is added due to RenderScript limitations I faced.
		// If bitmap width is not multiple of 4 - in RenderScript
		// index = y * width
		// does not calculate correct index for line start index.
		width = width & ~0x03;
		width = Math.max(width, 1);
		height = Math.max(height, 1);

		if (mBitmap == null || mBitmap.getWidth() != width
				|| mBitmap.getHeight() != height) {
			mBitmap = Bitmap.createBitmap(width, height,
					Bitmap.Config.ARGB_8888);
			mMatrixScale.setScale((float) width / mView.getWidth(),
					(float) height / mView.getHeight());
			mMatrixScale.invert(mMatrixScaleInv);
		}
		int dx = -(Math.min(0, mView.getLeft()) + mRectVisibleGlobal.left);
		int dy = -(Math.min(0, mView.getTop()) + mRectVisibleGlobal.top);
		mCanvas.restoreToCount(1);
		mCanvas.setBitmap(mBitmap);

		mCanvas.setMatrix(mMatrixScale);
		mCanvas.translate(dx, dy);
		mCanvas.save();
		mView.getRootView().draw(mCanvas);
		return mBitmap;
	}

	public int dip2px(Context context, int a) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (a * scale + 0.5f);
	}
}
